﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using CuteRibs.WowArmory.ViewModels;
using Microsoft.Phone.Controls;

namespace CuteRibs.WowArmory.Views
{
	public partial class RealmSearchPageView : PageBase
	{
		private RealmSearchPageViewModel viewModel { get { return this.ViewModel as RealmSearchPageViewModel; } }

		public RealmSearchPageView()
		{
			InitializeComponent();
		}

		private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var pivot = sender as Pivot;
			this.viewModel.SwitchView(pivot.SelectedIndex);
		}

		private void Button_Tap(object sender, EventArgs e)
		{
			var tbRealm = this.FindName("tbRealm") as TextBox;
			this.viewModel.FilterRealms(tbRealm.Text.Trim());
		}

		private void btnSearch_Click(object sender, EventArgs e)
		{
			var tbRealm = this.FindName("tbRealm") as TextBox;
			this.viewModel.FilterRealms(tbRealm.Text.Trim());
		}

		private void Grid_Tap(object sender, EventArgs e)
		{
			var element = sender as FrameworkElement;
		}

		private void TextBox_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter)
			{
				this.Focus();
				this.viewModel.FilterRealms((sender as TextBox).Text.Trim());
			}
		}

		private void TextBlock_Loaded(object sender, RoutedEventArgs e)
		{
			var term = this.viewModel.Term;

			if (!string.IsNullOrWhiteSpace(term))
			{
				var textBlock = sender as TextBlock;
				var type = textBlock.Inlines.Last();
				var name = textBlock.Tag as string;
				var index = name.ToLower().IndexOf(term.ToLower());
				var text1 = name.Substring(0, index);
				var text2 = name.Substring(index, term.Length);
				var text3 = name.Substring(index + term.Length);

				textBlock.Inlines.Clear();

				if (text1.Length > 0)
				{
					textBlock.Inlines.Add(new Run { Text = text1 });
				}

				if (text2.Length > 0)
				{
					textBlock.Inlines.Add(new Run { Text = text2, Foreground = App.Current.Resources["Color_Yellow"] as Brush });
				}

				if (text3.Length > 0)
				{
					textBlock.Inlines.Add(new Run { Text = text3 });
				}

				textBlock.Inlines.Add(type);
			}
		}

		private void mnuAdd_Click(object sender, EventArgs e)
		{
			var control = sender as FrameworkElement;
			var vm = control.DataContext as RealmViewModel;
			this.viewModel.AddRealm(vm);
		}
	}
}